{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "b''"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import requests\n",
    "# 1.创建人脸列表\n",
    "faceListId = \"list_22\" # 设置人脸列表ID\n",
    "create_facelists_url =\"https://fpkapi.cognitiveservices.azure.com/face/v1.0/facelists/{}\" # URL（见API文档）\n",
    "subscription_key =\"64a33a0983774e318e3fb211c70a94a7\" # 密钥\n",
    "# 请求头\n",
    "headers = {\n",
    "    'Content-Type': 'application/json',\n",
    "    'Ocp-Apim-Subscription-Key': subscription_key,\n",
    "}\n",
    "# 相关信息及识别模型的选用\n",
    "data = {\n",
    "  \"name\": \"sample_list\",\n",
    "  \"userData\": \"相册\",\n",
    "  \"recognitionModel\": \"recognition_03\"\n",
    "}\n",
    "# 发送请求\n",
    "r_create = requests.put(create_facelists_url.format(faceListId), headers=headers, json=data)\n",
    "r_create.content"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "200"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 2.添加人脸\n",
    "add_face_url =\"https://fpkapi.cognitiveservices.azure.com/face/v1.0/facelists/{}/persistedfaces\"\n",
    "assert subscription_key\n",
    "headers = {\n",
    "    'Content-Type': 'application/json',\n",
    "    'Ocp-Apim-Subscription-Key': subscription_key,\n",
    "}\n",
    "# 人脸相片地址\n",
    "img_url =\"https://gitee.com/fanpeikun/my-ku/raw/master/41c37c09abd946e4da3abaf6f7f1234f.jpg\"\n",
    "# 人脸数据\n",
    "params_add_face={\n",
    "    \"userData\":\"flower jisoo\"\n",
    "}\n",
    "# 发送请求\n",
    "r_add_face = requests.post(add_face_url.format(faceListId),headers=headers,params=params_add_face,json={\"url\":img_url})\n",
    "r_add_face.status_code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'persistedFaceId': '9f848c50-e613-498f-b3ba-778b4f4cf73e'}"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "r_add_face.json() # 返回persistedFaceId"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 封装成函数方便添加图片\n",
    "def AddFace(img_url=str,userData=str):\n",
    "    add_face_url =\"https://fpkapi.cognitiveservices.azure.com/face/v1.0/facelists/{}/persistedFaces\"\n",
    "    assert subscription_key\n",
    "    headers = {\n",
    "        # Request headers\n",
    "        'Content-Type': 'application/json',\n",
    "        'Ocp-Apim-Subscription-Key': subscription_key,\n",
    "    }\n",
    "    img_url = img_url\n",
    "    params_add_face={\n",
    "        \"userData\":userData\n",
    "    }\n",
    "    r_add_face = requests.post(add_face_url.format(faceListId),headers=headers,params=params_add_face,json={\"url\":img_url})\n",
    "    return r_add_face.status_code #返回出状态码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "200"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "AddFace(\"https://gitee.com/fanpeikun/my-ku/raw/master/f692a03cb7fbc3545eac264b18fc2367.jpeg\",\"Billie\")\n",
    "AddFace(\"https://gitee.com/fanpeikun/my-ku/raw/master/20191214152337.jpg\",\"jisoo\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'faceId': 'c251b377-b2d3-485a-9e71-cebea1586dce',\n",
       "  'faceRectangle': {'top': 207, 'left': 599, 'width': 311, 'height': 311},\n",
       "  'faceAttributes': {'smile': 0.01,\n",
       "   'headPose': {'pitch': 8.8, 'roll': 16.9, 'yaw': -18.8},\n",
       "   'gender': 'female',\n",
       "   'age': 22.0,\n",
       "   'facialHair': {'moustache': 0.0, 'beard': 0.0, 'sideburns': 0.0},\n",
       "   'glasses': 'NoGlasses',\n",
       "   'emotion': {'anger': 0.0,\n",
       "    'contempt': 0.0,\n",
       "    'disgust': 0.0,\n",
       "    'fear': 0.0,\n",
       "    'happiness': 0.01,\n",
       "    'neutral': 0.988,\n",
       "    'sadness': 0.001,\n",
       "    'surprise': 0.0},\n",
       "   'blur': {'blurLevel': 'low', 'value': 0.07},\n",
       "   'exposure': {'exposureLevel': 'goodExposure', 'value': 0.66},\n",
       "   'noise': {'noiseLevel': 'medium', 'value': 0.41},\n",
       "   'makeup': {'eyeMakeup': True, 'lipMakeup': True},\n",
       "   'accessories': [{'type': 'headwear', 'confidence': 1.0}],\n",
       "   'occlusion': {'foreheadOccluded': True,\n",
       "    'eyeOccluded': False,\n",
       "    'mouthOccluded': False},\n",
       "   'hair': {'bald': 0.0, 'invisible': True, 'hairColor': []}}}]"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 3.检测人脸\n",
    "face_api_url = 'https://fpkapi.cognitiveservices.azure.com/face/v1.0/detect'\n",
    "image_url = 'https://gitee.com/fanpeikun/my-ku/raw/master/41c37c09abd946e4da3abaf6f7f1234f.jpg'\n",
    "headers = {'Ocp-Apim-Subscription-Key': subscription_key}\n",
    "# 请求参数\n",
    "params = {\n",
    "    'returnFaceId': 'true',\n",
    "    'returnFaceLandmarks': 'false',\n",
    "    # 选择模型\n",
    "    'recognitionModel':'recognition_03',#此参数需与facelist参数一致\n",
    "    'detectionModel':'detection_01',\n",
    "    # 可选参数，请仔细阅读API文档\n",
    "    'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise',\n",
    "}\n",
    "response = requests.post(face_api_url, params=params,headers=headers, json={\"url\": image_url})\n",
    "response.json()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'persistedFaceId': '9f848c50-e613-498f-b3ba-778b4f4cf73e',\n",
       "  'confidence': 1.0},\n",
       " {'persistedFaceId': '20438fb7-11f0-4f0f-a66c-e96ffb8ed1f5',\n",
       "  'confidence': 0.14733},\n",
       " {'persistedFaceId': '2c210b2d-c72e-4690-b321-66d0218d2f53',\n",
       "  'confidence': 0.09571}]"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 4.返回人脸相似置信度\n",
    "findsimilars_url = \"https://fpkapi.cognitiveservices.azure.com/face/v1.0/findsimilars\"\n",
    "# 请求正文 faceID需要先检测一张照片获取\n",
    "data_findsimilars = {\n",
    "    \"faceId\":\"c251b377-b2d3-485a-9e71-cebea1586dce\", #取上方的faceID\n",
    "    \"faceListId\": \"list_22\",\n",
    "    \"maxNumOfCandidatesReturned\": 10,\n",
    "    \"mode\": \"matchFace\" #matchPerson #一种为验证模式，一种为相似值模式\n",
    "    }\n",
    "r_findsimilars = requests.post(findsimilars_url,headers=headers,json=data_findsimilars)\n",
    "r_findsimilars.json()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'persistedFaces': [{'persistedFaceId': '9f848c50-e613-498f-b3ba-778b4f4cf73e',\n",
       "   'userData': 'flower jisoo'},\n",
       "  {'persistedFaceId': '2c210b2d-c72e-4690-b321-66d0218d2f53',\n",
       "   'userData': 'Billie'},\n",
       "  {'persistedFaceId': '20438fb7-11f0-4f0f-a66c-e96ffb8ed1f5',\n",
       "   'userData': 'jisoo'}],\n",
       " 'faceListId': 'list_22',\n",
       " 'name': 'sample_list',\n",
       " 'userData': '相册'}"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 查看列表\n",
    "get_facelist_url = \"https://fpkapi.cognitiveservices.azure.com/face/v1.0/facelists/{}\"\n",
    "r_get_facelist = requests.get(get_facelist_url.format(faceListId),headers=headers)\n",
    "r_get_facelist.json()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>persistedFaceId</th>\n",
       "      <th>userData</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>9f848c50-e613-498f-b3ba-778b4f4cf73e</td>\n",
       "      <td>flower jisoo</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2c210b2d-c72e-4690-b321-66d0218d2f53</td>\n",
       "      <td>Billie</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>20438fb7-11f0-4f0f-a66c-e96ffb8ed1f5</td>\n",
       "      <td>jisoo</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                        persistedFaceId      userData\n",
       "0  9f848c50-e613-498f-b3ba-778b4f4cf73e  flower jisoo\n",
       "1  2c210b2d-c72e-4690-b321-66d0218d2f53        Billie\n",
       "2  20438fb7-11f0-4f0f-a66c-e96ffb8ed1f5         jisoo"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 用Pandas简化数据\n",
    "import pandas as pd\n",
    "# 返回facelist数据\n",
    "adf = pd.json_normalize(r_get_facelist.json()[\"persistedFaces\"])\n",
    "adf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>persistedFaceId</th>\n",
       "      <th>confidence</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>9f848c50-e613-498f-b3ba-778b4f4cf73e</td>\n",
       "      <td>1.00000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>20438fb7-11f0-4f0f-a66c-e96ffb8ed1f5</td>\n",
       "      <td>0.14733</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>2c210b2d-c72e-4690-b321-66d0218d2f53</td>\n",
       "      <td>0.09571</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                        persistedFaceId  confidence\n",
       "0  9f848c50-e613-498f-b3ba-778b4f4cf73e     1.00000\n",
       "1  20438fb7-11f0-4f0f-a66c-e96ffb8ed1f5     0.14733\n",
       "2  2c210b2d-c72e-4690-b321-66d0218d2f53     0.09571"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 返回相似度数据\n",
    "bdf = pd.json_normalize(r_findsimilars.json())# 升级pandas才能运行\n",
    "bdf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>persistedFaceId</th>\n",
       "      <th>userData</th>\n",
       "      <th>confidence</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>9f848c50-e613-498f-b3ba-778b4f4cf73e</td>\n",
       "      <td>flower jisoo</td>\n",
       "      <td>1.00000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>20438fb7-11f0-4f0f-a66c-e96ffb8ed1f5</td>\n",
       "      <td>jisoo</td>\n",
       "      <td>0.14733</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2c210b2d-c72e-4690-b321-66d0218d2f53</td>\n",
       "      <td>Billie</td>\n",
       "      <td>0.09571</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                        persistedFaceId      userData  confidence\n",
       "0  9f848c50-e613-498f-b3ba-778b4f4cf73e  flower jisoo     1.00000\n",
       "2  20438fb7-11f0-4f0f-a66c-e96ffb8ed1f5         jisoo     0.14733\n",
       "1  2c210b2d-c72e-4690-b321-66d0218d2f53        Billie     0.09571"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#合并\n",
    "pd.merge(adf, bdf,how='inner', on='persistedFaceId').sort_values(by=\"confidence\",ascending = False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 5.删除人脸/人脸列表\n",
    "faceListId = \"list_22\" # 需要删除的人脸列表\n",
    "# 删除列表内人脸\n",
    "delete_face_url = \"https://fpkapi.cognitiveservices.azure.com/face/v1.0/facelists/{}/persistedfaces/{}\"\n",
    "assert subscription_key\n",
    "# 获取上面的persistedFaceId\n",
    "persistedFaceId = r_add_face.json()[\"persistedFaceId\"] \n",
    "headers = {\n",
    "    'Content-Type': 'application/json',\n",
    "    'Ocp-Apim-Subscription-Key': subscription_key,\n",
    "}\n",
    "# 注意requests请求为delete\n",
    "r_delete_face = requests.delete(delete_face_url.format(faceListId,persistedFaceId),headers=headers)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 删除人脸列表\n",
    "delete_facelist_url = \"https://fpkapi.cognitiveservices.azure.com/face/v1.0/facelists/{}\"\n",
    "assert subscription_key\n",
    "headers = {\n",
    "    'Content-Type': 'application/json',\n",
    "    'Ocp-Apim-Subscription-Key': subscription_key,\n",
    "}\n",
    "r_delete_facelist = requests.delete(delete_facelist_url.format(faceListId),headers=headers)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Response [200]>"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "r_delete_face"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Response [200]>"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "r_delete_facelist"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
